// Code scaffolded by goctl. Safe to edit.
// goctl 1.9.1

package fileTag

import (
	"audio-server/internal/model"
	"audio-server/internal/sqlutil"
	"context"
	"errors"
	"time"

	"audio-server/internal/svc"
	"audio-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type FileTagSaveLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewFileTagSaveLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FileTagSaveLogic {
	return &FileTagSaveLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *FileTagSaveLogic) FileTagSave(req *types.FileTagSaveReq) (resp bool, err error) {
	id := sqlutil.GetUserId(l.ctx)
	if id == 0 {
		return false, errors.New("请先登录")
	}
	tag := model.SysFileTag{
		TagId:      req.TagId,
		Title:      req.Title,
		UserId:     id,
		CreateTime: time.Now(),
	}
	tagModel := model.NewSysFileTagModel(l.svcCtx.Conn)
	_, err = tagModel.FindByName(l.ctx, tag.Title, id)
	if err != nil {
		return false, errors.New("已存在该标签")
	}
	if tag.TagId == 0 {
		_, err = tagModel.Insert(l.ctx, &tag)
		if err != nil {
			return false, err
		}
	} else {
		updateErr := tagModel.Update(l.ctx, &tag)
		if updateErr != nil {
			return false, updateErr
		}
	}

	return true, nil
}
